package com.heima.article.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.es.ApArticleSearch;
import com.heima.article.es.ArticleRepository;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.common.dto.ResponseResult;
import com.heima.common.minio.MinIOService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.data.elasticsearch.core.query.GetQuery;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("test")
public class TestController {

    @Autowired
    private MinIOService minIOService;

    @Autowired
    private IApArticleService articleService;

    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private Configuration configuration;

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;

    /**
     * 创建索引库
     * @return
     */
    @GetMapping("/es/index")
    public ResponseResult createIndex(){
        elasticsearchRestTemplate.createIndex(ApArticleSearch.class);
        return ResponseResult.okResult("索引创建完成");
    }

    /**
     * 添加映射关系
     * @return
     */
    @GetMapping("/es/mapping")
    public ResponseResult addMapping(){
        elasticsearchRestTemplate.putMapping(ApArticleSearch.class);
        return ResponseResult.okResult("添加映射关系完成");
    }
    @GetMapping("/es/add/{id}")
    public ResponseResult addDoc(@PathVariable("id") Long id){
        //根据id从数据库中查询文章
        ApArticle apArticle = articleService.getById(id);
        //转换成文章搜索对象
        ApArticleSearch articleSearch = new ApArticleSearch();
        BeanUtils.copyProperties(apArticle,articleSearch);
        //保存到es中
        IndexQuery query = new IndexQuery();
        query.setId(articleSearch.getId().toString());
        query.setObject(articleSearch);
        elasticsearchRestTemplate.index(query);
        return ResponseResult.okResult("添加文档完成");
    }

    @GetMapping("/es/get/{id}")
    public ResponseResult getDoc(@PathVariable("id") String id){
        GetQuery query = new GetQuery();
        query.setId(id);
        ApArticleSearch articleSearch = elasticsearchRestTemplate.queryForObject(query, ApArticleSearch.class);
        System.out.println(articleSearch);
        return ResponseResult.okResult("查询文档完成");
    }

    @GetMapping("/es/del/{id}")
    public ResponseResult delDoc(@PathVariable("id") String id){
        elasticsearchRestTemplate.delete(ApArticleSearch.class,id);
        return ResponseResult.okResult("删除文档完成");
    }

    @Autowired
    private ArticleRepository articleRepository;

    /**
     * 初始化所有已存在的文章
     * @param
     * @return
     */
    @GetMapping("/es/repository")
    public ResponseResult addArticle(){
        //查询所有文章
        List<ApArticle> list = articleService.list();
        List<ApArticleSearch> articleSearchs = new ArrayList<>();
        for (ApArticle article : list) {
            //转换成文章搜索对象
            ApArticleSearch articleSearch = new ApArticleSearch();
            BeanUtils.copyProperties(article,articleSearch);
            articleSearchs.add(articleSearch);
        }
        //保存到es中
        articleRepository.saveAll(articleSearchs);
        return ResponseResult.okResult("添加文档完成");
    }
    @GetMapping("/html/{id}")

    public ResponseResult createHtml(@PathVariable("id") Long id) throws IOException, TemplateException {
        //根据id查询文章数据
        ApArticle apArticle = articleService.getById(id);
        //查询文章内容表
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId,id);
        ApArticleContent articleContent = contentService.getOne(query);
        //使用freemarker生成html文件
        //获取模板
        Template template = configuration.getTemplate("article.ftl");
        //准备数据
        Map<String ,Object> map = new HashMap<>();
        map.put("content", JSON.parseArray(articleContent.getContent()));
        //合并模板和数据
        Writer writer = new StringWriter();
        template.process(map,writer);

        //将文件存放到minio中
        String name = id+".html";
        //构建输入流
        InputStream is = new ByteArrayInputStream(writer.toString().getBytes());
        String url = minIOService.upload(name, is, "text/html");

        //将minio返回的地址保存到文章表中
        apArticle.setStaticUrl(url);
        articleService.updateById(apArticle);
        return ResponseResult.okResult();
    }


}
